package com.lifesting.front;

import java.io.IOException;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseId;

import com.sun.faces.renderkit.html_basic.HtmlBasicRenderer;

public class RnsRender extends HtmlBasicRenderer {
	public static final String RENDER_TYPE = "com.lifesting.render.rownumbercount";

	@Override
	public void encodeBegin(FacesContext context, UIComponent component)
			throws IOException {
		super.encodeBegin(context, component);
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("p", component);
		String id = component.getClientId(context);
		writer.writeAttribute("id", id, "id");
		writer.write(" " + getText(component) + ": ");
		writer.startElement("input", component);
		writer.writeAttribute("id", id + ".1", "number_id");
		writer.writeAttribute("name", id+".1", "number_name");
		writer.writeAttribute("type", "text", "number_type");
		writer.writeAttribute("size", "5", "number_size");
		writer.writeAttribute("value", getRowsCount(component), "number_value");
		writer.endElement("input");
		writer.write("  ");
		writer.startElement("input", component);
		writer.writeAttribute("name", id+".2", "sb_name");
		writer.writeAttribute("type", "submit", "sb_type");
		writer.writeAttribute("value", "确定", "sb_value");
		writer.endElement("input");

	}
	private Table getTable(UIComponent component)
	{
		assert (component instanceof Rns);
		String table_id = ((Rns)component).getTableFor();
		UIComponent table_component = component.getParent().findComponent(table_id);
		assert (table_component != null);
		assert (table_component instanceof Table);
		return ((Table)table_component);
	}
	//保证rns与table在同一级别
	private Object getRowsCount(UIComponent component) throws IOException{
		return getTable(component).getRowsCount();		
	}
	private String getText(UIComponent component) {
		assert (component instanceof Rns);
		return ((Rns)component).getText();
	}

	@Override
	public void encodeEnd(FacesContext context, UIComponent component)
			throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.endElement("p");
	}

	@Override
	public void decode(FacesContext context, UIComponent component) {
		super.decode(context, component);
		String clientId = component.getClientId(context);
		assert (clientId != null);
		Map<String, String> requestMap = context.getExternalContext()
				.getRequestParameterMap();
		String btn_id = clientId+".2";
		if (requestMap.containsKey(btn_id))
		{
			Table t = getTable(component);
			RnsEvent evt = new RnsEvent(t);
			String nb = requestMap.get(clientId+".1");
			evt.setNumber(Integer.valueOf(nb));
			evt.setPhaseId(PhaseId.INVOKE_APPLICATION);
			t.queueEvent(evt);
		}
	}
}
